package com.ultrapower.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ultrapower.commons.base.BaseController;
import com.ultrapower.commons.result.PageInfo;
import com.ultrapower.commons.shiro.PasswordHash;
import com.ultrapower.commons.shiro.ShiroUser;
import com.ultrapower.commons.utils.BeanUtils;
import com.ultrapower.commons.utils.StringUtils;
import com.ultrapower.model.Role;
import com.ultrapower.model.TSysuser;
import com.ultrapower.model.vo.UserVo;
import com.ultrapower.service.IUserService;

/**
 * @description：用户管理
 * @author：zhixuan.wang
 * @date：2015/10/1 14:51
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordHash passwordHash;

    /**
     * 用户管理页
     *
     * @return
     */
    @GetMapping("/manager")
    public String manager() {
        return "admin/user/user";
    }
    
    /**
     * 经理——成员管理
     *
     * @return
     */
    @GetMapping("/member")
    public String member() {
        return "admin/member/member";
    }

    /**
     * 用户管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(UserVo userVo, Integer page, Integer limit, String sort, String order) {
    	sort = "createTime";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
        if (userVo.getOrganizationId() != null) {
            condition.put("organizationId", userVo.getOrganizationId());
        }
        if (userVo.getCreatedateStart() != null) {
            condition.put("startTime", userVo.getCreatedateStart());
        }
        if (userVo.getCreatedateEnd() != null) {
            condition.put("endTime", userVo.getCreatedateEnd());
        }
        pageInfo.setCondition(condition);
        userService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 用户管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/menmberList")
    @ResponseBody
    public Object menmberList(UserVo userVo, Integer page, Integer limit, String sort, String order, HttpServletRequest request) {
    	sort = "createTime";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        
        condition.put("manager", getUserId());
        
        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
     
        pageInfo.setCondition(condition);
        userService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * 添加成员页
     *
     * @return
     */
    @GetMapping("/addMember")
    public String addMember() {
        return "admin/member/addMember";
    }
    
    /**
     * 待添加成员列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/outsiderList")
    @ResponseBody
    public Object allMemberList(UserVo userVo, Integer page, Integer limit, String sort, String order, HttpServletRequest request) {
    	sort = "createTime";
    	order = "asc";
        PageInfo pageInfo = new PageInfo(page, limit, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        
        condition.put("manager", user.getId());
        
        if (StringUtils.isNotBlank(userVo.getName())) {
            condition.put("name", userVo.getName());
        }
         
        pageInfo.setCondition(condition);
        userService.selectOutsider(pageInfo);
        return pageInfo;
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage")
    public String addPage() {
//    	Object res = organizationService.selectTreeGrid();
//    	JSONObject jbObject=new JSONObject();
//    	jbObject.put("list",res);
//    	model.addAttribute("list",res);
        return "admin/user/userAdd";
    }
    
    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Object add(UserVo userVo) {
    	String maxEId = userService.selectMaxEId();
    	String eId = "EI"+(Integer.parseInt(maxEId.substring(2))+1);
        List<TSysuser> list = userService.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            return renderError("登录名已存在!");
        }
        String salt = StringUtils.getUUId();
        String pwd = passwordHash.toHex(userVo.getPassword(), salt);
        userVo.setSalt(salt);
        userVo.setPassword(pwd);
        userVo.setEmployeeId(eId);
        userService.insertByVo(userVo);
        return renderSuccess("添加成功");
    }

    /**
     * 编辑用户页
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/editPage")
    public String editPage(Model model, Long id) {
        UserVo userVo = userService.selectVoById(id);
        List<Role> rolesList = userVo.getRolesList();
        List<Long> ids = new ArrayList<Long>();
        for (Role role : rolesList) {
            ids.add(role.getId());
        }
        model.addAttribute("roleIds", ids);
        model.addAttribute("user", userVo);
        return "admin/user/userEdit";
    }

    /**
     * 编辑用户
     *
     * @param userVo
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/edit")
    @ResponseBody
    public Object edit(@Valid UserVo userVo) {
        List<TSysuser> list = userService.selectByLoginName(userVo);
        if (list != null && !list.isEmpty()) {
            return renderError("登录名已存在!");
        }
        // 更新密码
        if (StringUtils.isNotBlank(userVo.getPassword())) {
            TSysuser user = userService.selectById(userVo.getId());
            String salt = user.getSalt();
            String pwd = passwordHash.toHex(userVo.getPassword(), salt);
            userVo.setPassword(pwd);
        }
        userService.updateByVo(userVo);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 用户添加经理id
     *
     * @param userVo
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/addMember")
    @ResponseBody
    public Object addMember(Long id) {
    	UserVo userVo = userService.selectVoById(id);
    	TSysuser user = BeanUtils.copy(userVo, TSysuser.class);
    	ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
    	user.setManager(shiroUser.getId());
        userService.updateById(user);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 用户删除经理id
     *
     * @param userVo
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/delMember")
    @ResponseBody
    public Object delMember(Long id) {
    	UserVo userVo = userService.selectVoById(id);
    	TSysuser user = BeanUtils.copy(userVo, TSysuser.class);
    	user.setManager(0L);
        userService.updateById(user);
        return renderSuccess("修改成功！");
    }
    
    /**
     * 修改密码页
     *
     * @return
     */
    @GetMapping("/editPwdPage")
    public String editPwdPage() {
        return "admin/user/userEditPwd";
    }

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param pwd
     * @return
     */
    @PostMapping("/editUserPwd")
    @ResponseBody
    public Object editUserPwd(String oldPwd, String pwd) {
        TSysuser user = userService.selectById(getUserId());
        String salt = user.getSalt();
        if (!user.getPassword().equals(passwordHash.toHex(oldPwd, salt))) {
            return renderError("老密码不正确!");
        }
        userService.updatePwdByUserId(getUserId(), passwordHash.toHex(pwd, salt));
        return renderSuccess("密码修改成功！");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        Long currentUserId = getUserId();
        if (id == currentUserId) {
            return renderError("不可以删除自己！");
        }
        userService.deleteUserById(id);
        return renderSuccess("删除成功！");
    }
    
    /**
     * 获取用户总数
     *
     * @return
     */
    @GetMapping("/userListCount")
    @ResponseBody
    public int userListCount() {
        int count = userService.selectListCount();
        return count;
    }
}